<template>
  <div>
    <el-dialog
      ref="detailDialog"
      title="工人信息"
      :visible="popVisible"
      :close-on-click-modal="false"
      @close="onCancel"
      class="detail-dialog"
    >
      <el-descriptions title="基本信息">
        <div slot="title">
          基本信息
          <el-tag :class="workerData.status === 'QUIT_JOB' ? 'disabled' : ''">
            {{ workerData.status | workerStatusFilter }}
          </el-tag>
        </div>

        <el-descriptions-item v-for="item in columns" :key="item.key" class="mb-20" :label="item.label">
          <span class="gray" slot="label">{{ item.label }}</span>
          <span v-if="item.key === 'gender'">{{ workerData[item.key] | genderFilter }}</span>
          <span v-else-if="item.key === 'education'">{{ workerData[item.key] | educationFilter }}</span>
          <span v-else-if="item.datatype === 'time'">
            {{ workerData[item.key] | timeFilter(item.format) }}
          </span>
          <span v-else>{{ workerData[item.key] }}</span>
        </el-descriptions-item>
      </el-descriptions>

      <div class="el-descriptions">
        <div class="el-descriptions__header">
          <div class="el-descriptions__title">合同信息  <el-link type="primary" v-if="workerData.contractAmount > 3" @click="moreContracts">  更多合同 >></el-link></div>

        </div>
        <div class="el-descriptions__body">
          <el-table
            :data="workerData.contractList.slice(0, 5)"
            element-loading-text="加载中"
            border
            fit
            highlight-current-row
            slot="body"
          >
            <el-table-column label="合同名称" min-width="120" :show-overflow-tooltip="true" align="center">
              <template slot-scope="scope">
                <el-button type="text" class="text-ellipsis" @click="handleContractPreview(scope.row.contractId)">{{
                  scope.row.contractName
                }}</el-button>
              </template>
            </el-table-column>
            <el-table-column label="合同创建时间" width="180" :show-overflow-tooltip="true" align="center">
              <template slot-scope="scope">
                {{ scope.row.createdOn | timeFilter }}
              </template>
            </el-table-column>
            <el-table-column label="截止签署时间" width="180" :show-overflow-tooltip="true" align="center">
              <template slot-scope="scope">
                {{ scope.row.deadline | timeFilter }}
              </template>
            </el-table-column>
            <el-table-column label="合同状态" min-width="120" :show-overflow-tooltip="true" align="center">
              <template slot-scope="scope">
                {{ scope.row.status | flowStatusFilter }}
              </template>
            </el-table-column>
          </el-table>
        </div>
      </div>

      <div class="el-descriptions">
        <div class="el-descriptions__header">
          <div class="el-descriptions__title">派遣轨迹</div>
        </div>
        <div class="el-descriptions__body">
          <el-table
            :loading="sendListLoading"
            :data="sendList || []"
            element-loading-text="加载中"
            border
            fit
            highlight-current-row
          >
            <el-table-column type="index" label="序号" width="50" align="center"> </el-table-column>
            <el-table-column label="用工单位" min-width="120" :show-overflow-tooltip="true" align="center">
              <template slot-scope="scope">
                {{ scope.row.tenantName }}
              </template>
            </el-table-column>
            <el-table-column label="派遣开始时间" min-width="120" :show-overflow-tooltip="true" align="center">
              <template slot-scope="scope">
                <span>{{ scope.row.startTime | timeFilter }}</span>
              </template>
            </el-table-column>
            <el-table-column label="派遣结束时间" min-width="120" :show-overflow-tooltip="true" align="center">
              <template slot-scope="scope">
                {{ scope.row.endTime | timeFilter }}
              </template>
            </el-table-column>
          </el-table>
          <el-pagination
            small
            layout="total,prev, pager, next"
            :total="sendTotalCount"
            :page-size="limit"
            @current-change="handleSendCurrentChange"
            :current-page.sync="currentPage"
          />
        </div>
      </div>

      <div class="form-footer" slot="footer">
        <el-button type="secondary" class="btn" @click.native.prevent="onCancel">关闭</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import { getDetail } from '@common/api/worker';
// import { getExternalLink } from '@common/api/staff';
import { getSendList } from '@common/api/send';

import { formatTime } from '@common/utils/time';
import { getColumns } from '@common/utils/worker';
import { GENDER, EDUCATION, WORKER_STATUS } from '@common/consts/worker';

export default {
  props: {
    Id: {
      type: String,
      default() {
        return '';
      },
    },
    visible: {
      type: Boolean,
      default() {
        return false;
      },
    },
  },
  filters: {
    genderFilter(gender) {
      // 性别
      return gender ? GENDER.find(v => v.value === gender)?.label || '--' : '--';
    },
    educationFilter(edu) {
      // 学历
      return edu ? EDUCATION.find(v => v.value === edu)?.label || '--' : '--';
    },
    timeFilter(time) {
      if (time) return formatTime(time);
      return '--';
    },
    workerStatusFilter(status) {
      return WORKER_STATUS[status] || '未发起合同';
    },
    flowStatusFilter(status) {
      switch (status) {
        case 'INIT':
          return '待签署';
        case 'PART':
          return '签署中';
        case 'ALL':
          return '已签署';
        case 'REJECT':
          return '已拒签';
        case 'CANCEL':
          return '合同撤回';
        case 'WILLEXPIRE':
          return '合同即将过期';
        case 'DEADLINE':
          return '合同过期';
        case 'STOPPED':
          return '合同已终止';
        default:
          return '合同异常';
      }
    },
  },
  data() {
    return {
      loading: true,
      workerData: { contractList: [] },
      sendList: [],
      limit: 5,
      offset: 0,
      currentPage: 1,
      sendListLoading: true, // 派遣记录loading
      sendTotalCount: 0, // 派遣记录总数
    };
  },
  watch: {
    popVisible() {
      if (this.popVisible && this.Id) {
        this.fetchData({ Id: this.Id });
      }
    },
  },
  computed: {
    popVisible() {
      return this.visible;
    },
    columns() {
      return getColumns(['name', 'mobile', 'gender', 'age', 'idcardNo', 'education', 'birthPlace', 'address']);
    },
  },

  methods: {
    async fetchData() {
      const [detailRes, sendRes] = await Promise.all([
        getDetail({ Id: this.Id }),
        getSendList({
          limit: this.limit,
          offset: this.offset,
          workerId: this.Id,
          needTenantInfo: true,
        }),
      ]);
      if (detailRes?.data?.worker) {
        this.workerData = { ...detailRes.data.worker };
        this.sendList = sendRes?.data?.list;
        this.sendTotalCount = sendRes?.data?.totalCount || 0;
      } else {
        this.workerData = { contractList: [] };
      }
      this.sendListLoading = false;
      this.loading = false;
    },
    // 查看合同
    handleContractPreview(flowId) {
      if (flowId) {
        // const res = getExternalLink
        this.$router.push({
          path: `/contract/detail/${flowId}`,
        });
      } else {
        this.$$message({
          message: '暂不支持查看',
          type: 'warning',
        });
      }
    },
    // 派遣记录分页
    async handleSendCurrentChange(data) {
      this.sendListLoading = true;
      this.offset = (data - 1) * this.limit;
      this.currentPage = data;
      const sendInfo = await getSendList({
        offset: this.offset,
        limit: this.limit,
        needTenantInfo: true,
        workerId: this.Id,
      });
      this.sendList = sendInfo?.data?.list || [];
      this.sendListLoading = false;
    },
    moreContracts() {
      this.$router.push({
        name: 'labor',
        params: {
          contractName: this.workerData.name,
        },
      });
    },
    onCancel() {
      this.$emit('detailHide');
      this.offset = 0;
      this.sendList = [];
      this.totalCount = 0;
    },
  },
};
</script>
<style  lang="scss">
.box-card {
  margin-bottom: 10px;
}
.gray {
  color: #797979;
}

.mb-20 {
  margin-bottom: 20px;
}
.el-descriptions {
  margin-bottom: 20px;
  .gray {
    color: #333;
  }
  .disabled {
    color: #999;
    background: #eee;
  }
}
.detail-dialog .el-dialog__body{
  max-height: 600px;
  overflow-y: scroll;
}
</style>
